package com.xing.service.impl;

import com.xing.dao.ArticleMapper;
import com.xing.entity.pojo.Article;
import com.xing.entity.vo.AjaxMessage;
import com.xing.entity.vo.ArticlePage;
import com.xing.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,readOnly = false)
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;
    @Override
    public int deleteByPrimaryKey(String articleid) {
        return articleMapper.deleteByPrimaryKey(articleid);
    }

    @Override
    public int insert(Article record) {
        return articleMapper.insert(record);
    }

    @Override
    public int insertSelective(Article record) {
        return articleMapper.insertSelective(record);
    }

    @Override
    public Article selectByPrimaryKey(String articleid) {
        return articleMapper.selectByPrimaryKey(articleid);
    }

    @Override
    public int updateByPrimaryKeySelective(Article record) {
        return articleMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKeyWithBLOBs(Article record) {
        return articleMapper.updateByPrimaryKeyWithBLOBs(record);
    }

    @Override
    public int updateByPrimaryKey(Article record) {
        return articleMapper.updateByPrimaryKey(record);
    }

    @Override
    public ArticlePage findByPage(Integer currentPage, Integer rows ,String typeName, Byte newsState) {
        ArticlePage ArticlePage=new ArticlePage();
        //每页几条
        ArticlePage.setRows(rows);
        //总条数
        int count = articleMapper.findArticleTotalCount(typeName,newsState);
        ArticlePage.setTotalCount(count);

        int start=(currentPage-1)*rows;
        //每页的记录
        ArticlePage.setList(articleMapper.findArticleAll(start,rows,typeName,newsState) );
        //总页数
        ArticlePage.setTotalPage((count%rows==0)?(count/rows):(count/rows+1));
        //当前页
        ArticlePage.setCurrentPage(currentPage);
        return ArticlePage;
    }

    @Override
    public Article findByTitle(String title) {
        return articleMapper.findByTitle(title);
    }

    @Override
    public AjaxMessage fileUploadAdd(Article article, MultipartFile multipartFile, HttpServletRequest request, HttpSession session) {
        AjaxMessage ajaxMessage=new AjaxMessage();
        if (!multipartFile.isEmpty()) {
            String filename = multipartFile.getOriginalFilename();
            String suffix = filename.substring(filename.indexOf("."));
            if (multipartFile.getSize() < 10485760) {
                List<String> list = Arrays.asList(".jpg", ".jpeg", ".tif", ".png");
                if (list.contains(suffix)) {
                    String realPath = request.getServletContext().getRealPath("/upload/");
                    String paths = UUID.randomUUID().toString();
                    SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
                    StringBuilder builder = new StringBuilder(dateFormat.format(new Date()));
                    builder.append("/");
                    String[] split = paths.split("-");
                    for (int i = 0; i < split.length-1; i++) {
                        builder.append(split[i]).append("/");
                    }
                    realPath+=builder.toString();

                    File file = new File(realPath);
                    if (!file.exists()) {
                        file.mkdirs();
                    }
                    String fileCurName= split[split.length-1]+suffix;
                    File file1 = new File(file, fileCurName);
                    try {
                        multipartFile.transferTo(file1);
                        article.setNewsImgUrl("/upload/"+builder.toString()+"/"+fileCurName);
                        article.setNewsState((byte) 0);
                        article.setNewsId(UUID.randomUUID().toString());
                        article.setNewsPublishTime(new Date());
                        article.setUserId((String) session.getAttribute("userId"));
                        int i = articleMapper.insertSelective(article);
                        if(i>0){
                            ajaxMessage.setSuccess(true).setCode(200).setMessage("上传成功");
                        }else {
                            ajaxMessage.setSuccess(false).setCode(150).setMessage("上传失败");
                        }

                    } catch (IOException e) {
                        e.printStackTrace();
                        ajaxMessage.setSuccess(false).setCode(111).setMessage("图片上传失败");
                    }
                }else {
                    ajaxMessage.setSuccess(false).setCode(112).setMessage("图片类型不正确，应为jpg,jpeg,tif或png");
                }

            }else {
                ajaxMessage.setSuccess(false).setCode(113).setMessage("图片太大，上传失败");
            }

        }else {
            ajaxMessage.setSuccess(false).setCode(120).setMessage("图片不能为空");
        }
        return ajaxMessage;
    }

    @Override
    public AjaxMessage updataAjaxArticle(Article article, MultipartFile multipartFile, HttpServletRequest request) {
        AjaxMessage ajaxMessage=new AjaxMessage();
        if (!multipartFile.isEmpty()) {
            String filename = multipartFile.getOriginalFilename();
            String suffix = filename.substring(filename.indexOf("."));
            if (multipartFile.getSize() < 10485760) {
                List<String> list = Arrays.asList(".jpg", ".jpeg", ".tif", ".png");
                if (list.contains(suffix)) {
                    String realPath = request.getServletContext().getRealPath("/upload/");
                    String paths = UUID.randomUUID().toString();
                    SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
                    StringBuilder builder = new StringBuilder(dateFormat.format(new Date()));
                    builder.append("/");
                    String[] split = paths.split("-");
                    for (int i = 0; i < split.length-1; i++) {
                        builder.append(split[i]).append("/");
                    }
                    realPath+=builder.toString();

                    File file = new File(realPath);
                    if (!file.exists()) {
                        file.mkdirs();
                    }
                    String fileCurName= split[split.length-1]+suffix;
                    File file1 = new File(file, fileCurName);
                    try {
                        multipartFile.transferTo(file1);
                        article.setNewsImgUrl("/upload/"+builder.toString()+"/"+fileCurName);
                        article.setNewsState((byte) 1);
                        int i = articleMapper.updateByPrimaryKeySelective(article);
                        if(i>0){
                            ajaxMessage.setSuccess(true).setCode(200).setMessage("发布成功");
                        }else {
                            ajaxMessage.setSuccess(false).setCode(150).setMessage("发布失败");
                        }

                    } catch (IOException e) {
                        e.printStackTrace();
                        ajaxMessage.setSuccess(false).setCode(111).setMessage("图片上传失败");
                    }
                }else {
                    ajaxMessage.setSuccess(false).setCode(112).setMessage("图片类型不正确，应为jpg,jpeg,tif或png");
                }

            }else {
                ajaxMessage.setSuccess(false).setCode(113).setMessage("图片太大，上传失败");
            }

        }else {
            article.setNewsState((byte) 1);
            int i = articleMapper.updateByPrimaryKeySelective(article);
            if(i>0){
                ajaxMessage.setSuccess(true).setCode(200).setMessage("发布成功");
            }else {
                ajaxMessage.setSuccess(false).setCode(150).setMessage("发布失败");
            }
        }
        return ajaxMessage;
    }


    @Override
    public Boolean deleteckArticle(String[] ids) {
        boolean flag=false;
        for (int i = 0; i <ids.length ; i++) {
            int i1 = articleMapper.deleteByPrimaryKey(ids[i]);
            if(i1>0){
                flag=true;
            }else {
                flag=false;
            }
        }
        return flag;
    }
}
